package com.shengyuan.manage_os.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

/**
 * Created by Administrator on 2016/12/19.
 */

public class FTPUpLoadUtils  extends Thread {
    @Override
    public void run() {
        FileInputStream in = null ;
        File dir = new File("/mnt/sdcard/DCIM/Camera/test/");
        File files[] = dir.listFiles();
        if(dir.isDirectory()) {
            for(int i=0;i<files.length;i++) {
                try {
                    in = new FileInputStream(files[i]);
                    boolean flag = uploadFile("17.8.119.77", 21, "android", "android",
                            "/", "412424123412341234_20130715120334_" + i + ".jpg", in);
                    System.out.println(flag);
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static boolean uploadFile(String url, int port, String username,
                                     String password, String path, String filename, InputStream input) {
        boolean success = false;
        FTPClient ftp = new FTPClient();


        try {
            int reply;
            ftp.connect(url, port);// 连接FTP服务器
            // 如果采用默认端口，可以使用ftp.connect(url)的方式直接连接FTP服务器
            ftp.login(username, password);//登录
            reply = ftp.getReplyCode();
            if (!FTPReply.isPositiveCompletion(reply)) {
                ftp.disconnect();
                return success;
            }
            ftp.changeWorkingDirectory(path);
            ftp.storeFile(filename, input);

            input.close();
            ftp.logout();
            success = true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ftp.isConnected()) {
                try {
                    ftp.disconnect();
                } catch (IOException ioe) {
                }
            }
        }
        return success;
    }
}

